package com.chongba.job.service;

import com.chongba.constant.Constant;
import com.chongba.entity.ResponseMessage;
import com.chongba.feign.ScheduleFeign;
import com.chongba.job.vote.SelectMaster;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
@Slf4j
public class JobService {

    @Autowired
    private ScheduleFeign scheduleFeign;

    @Autowired
    private SelectMaster selectMaster;


    //程序启动，注册主节点
    @PostConstruct
    public void registerFromZookeeper() {
        selectMaster.selectMaster(Constant.JOBPATH);
        System.out.println("注册节点成功");
    }

    /**
     * 改造：job模块高可用，单个模块多节点部署涉及主从备份，
     * 并且在刷新数据时，只有主节点才能执行，否则可能会发生数据异常
     */
    @Scheduled(cron = "*/1 * * * * ?")
    public void refresh() {
        if (selectMaster.checkMaster(Constant.JOBPATH)) {
            log.info("主节点刷新数据");
            try {
                ResponseMessage refresh = scheduleFeign.refresh();
                log.info("缓存数据刷新，{}", refresh);
            } catch (Exception e) {
                log.error("缓存数据刷新失败，{}", e.getMessage());
            }
        } else {
            log.info("从节点备用");
        }
    }
}
